package com.study.hot.jetpack.hilt

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.study.hot.databinding.ActivityHiltBinding
import com.study.hot.jetpack.hilt.model.Driver
import com.study.hot.jetpack.hilt.model.Truck
import com.study.hot.jetpack.hilt.use_in_mvvm.HiltViewModel
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.io.IOException
import javax.inject.Inject

/**
 * <pre>
 *     author : slx
 *     time   : 2020/11/24
 *     desc   :
 * </pre>
 */
@AndroidEntryPoint
class HiltActivity : AppCompatActivity() {

    @Inject
    lateinit var truck: Truck

    @Inject
    lateinit var okHttpClient: OkHttpClient

    @Inject
    lateinit var driver: Driver

    // 这样可以注入ViewModel，但是改变了以前ViewModel实例化的方式，不好
    // 对于jetpack组件中常用组件，hilt提供了独立的注入方式
    @Inject
    lateinit var hiltViewModel: HiltViewModel

    // 传统方式创建ViewModel
    /*val hiltViewModel2: HiltViewModel2 by lazy {
        ViewModelProvider(this).get(HiltViewModel2::class.java)
    }*/

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityHiltBinding.inflate(layoutInflater)
        with(binding) {
            setContentView(root)
            // 1.简单注入
            btnTest1.onClick {
                truck.deliver()
            }

            // 2.接口注入
            btnTest2.onClick {
                truck.deliverByGas()
            }

            // 3.注入第三方类库
            btnTest3.onClick {
                val request = Request.Builder()
                        .get()
                        .url("https://www.baidu.com")
                        .build()

                okHttpClient.newCall(request)
                        .enqueue(object : Callback {
                            override fun onFailure(call: Call, e: IOException) {
                                println("onFailure==>${e.message}")
                            }

                            override fun onResponse(call: Call, response: Response) {
                                val string = response.body
                                println("onSuccess==>$string")
                            }

                        })
            }

            // 注入MyApplication
            btnTest4.onClick {
                driver.testInjectMyApp()
            }
        }
    }

}